package com.zh.harmony.ormlitesample.dao;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.zh.harmony.ormlitesample.util.AppDatabaseHelper;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wally
 * @date 2022/08/11
 * Dao层基类
 */
public class BaseDao<T, ID> implements IDao<T, ID> {
    /**
     * 数据库操作Dao
     */
    protected final RuntimeExceptionDao<T, ID> mDao;

    public BaseDao(Class<T> entityClazz) {
        mDao = AppDatabaseHelper.getInstance().getRuntimeExceptionDao(entityClazz);
    }

    @Override
    public boolean insert(T entity) {
        return mDao.create(entity) > 0;
    }

    @Override
    public T createIfNotExists(T entity) {
        return mDao.createIfNotExists(entity);
    }

    @Override
    public boolean insertOrUpdate(T entity) {
        Dao.CreateOrUpdateStatus status = mDao.createOrUpdate(entity);
        return status.getNumLinesChanged() > 0;
    }

    @Override
    public boolean insertList(List<T> entities) {
        return mDao.create(entities) > 0;
    }

    @Override
    public boolean deleteById(ID id) {
        return mDao.deleteById(id) > 0;
    }

    @Override
    public boolean delete(T entity) {
        return mDao.delete(entity) > 0;
    }

    @Override
    public boolean deleteList(List<T> entities) {
        return mDao.delete(entities) > 0;
    }

    @Override
    public boolean deleteByIds(List<ID> ids) {
        return mDao.deleteIds(ids) > 0;
    }

    @Override
    public boolean deleteAll() {
        List<T> list = mDao.queryForAll();
        if (list == null || list.isEmpty()) {
            return true;
        }
        return mDao.delete(list) > 0;
    }

    @Override
    public boolean update(T entity) {
        return mDao.update(entity) > 0;
    }

    @Override
    public List<T> queryAll() {
        List<T> list = mDao.queryForAll();
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    @Override
    public T queryById(ID id) {
        return mDao.queryForId(id);
    }

    @Override
    public T queryLast() {
        try {
            List<T> result = mDao.queryBuilder()
                    .orderBy("id", false)
                    .limit(1L)
                    .query();
            if (result == null) {
                result = new ArrayList<>();
            }
            if (result.isEmpty()) {
                return null;
            }
            return result.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}